package com.android.demo.locationtest;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import java.util.List;

public class MainActivity extends AppCompatActivity {

  @BindView(R.id.tv_longitude) TextView tvLongitude;
  @BindView(R.id.tv_latitude) TextView tvLatitude;
  @BindView(R.id.tv_precision) TextView tvPrecision;
  @BindView(R.id.tv_get_location) TextView tvGetLocation;

  LocationListener locationListener;
  LocationManager locationManager;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    tvGetLocation.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        requestPermission();
      }
    });

    locationListener = new LocationListener() {
      @Override public void onLocationChanged(Location location) {
        //调用更新位置
        updateToNewLocation(location);
      }

      @Override public void onStatusChanged(String provider, int status, Bundle extras) {

      }

      @Override public void onProviderEnabled(String provider) {

      }

      @Override public void onProviderDisabled(String provider) {
        updateToNewLocation(null);
      }
    };
  }

  private void requestPermission() {
    //申请定位权限
    XXPermissions.with(this).permission(Permission.Group.LOCATION).request(new OnPermission() {
      @Override public void hasPermission(List<String> granted, boolean all) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
              != PackageManager.PERMISSION_GRANTED
              && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
              != PackageManager.PERMISSION_GRANTED) {

            // 获取位置服务
            String serviceName = Context.LOCATION_SERVICE;
            // 调用getSystemService()方法来获取LocationManager对象
            locationManager = (LocationManager) getSystemService(serviceName);
            // 指定LocationManager的定位方法
            String provider = LocationManager.GPS_PROVIDER;
            // 调用getLastKnownLocation()方法获取当前的位置信息
            Location location = locationManager.getLastKnownLocation(provider);

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0,
                locationListener);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,
                locationListener);
          }
        }
      }

      @Override public void noPermission(List<String> denied, boolean quick) {
      }
    });
  }

  private Location updateToNewLocation(Location location) {
    String latLongString;
    if (location != null) {
      //获取经度
      double lng = location.getLongitude();
      //获取纬度
      double lat = location.getLatitude();
      tvLongitude.setText(lng + "");
      tvLatitude.setText(lat + "");
      if (locationManager != null) {
        locationManager.removeUpdates(locationListener);
        locationManager = null;
      }
      if (locationListener != null) {
        locationListener = null;
      }
    } else {
      Toast.makeText(getApplicationContext(), "无法获取地理信息，请确认已开启定位权限并选择定位模式为GPS、WLAN和移动网络",
          Toast.LENGTH_SHORT).show();
    }
    return location;
  }
}
